package com.witframework.core;

import java.io.Serializable;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

import com.witframework.core.annotations.Wit;
import com.witframework.util.BeanUtils;
import com.witframework.util.TimestampBasedUIDGenerator;

public class WitSimpleNameGenerator implements IdentifierGenerator{
	
	public Serializable generate(SessionImplementor arg0, Object obj) throws HibernateException {
		Wit wit=obj.getClass().getAnnotation(Wit.class);
		if(wit!=null&&StringUtils.isNotEmpty(wit.cnproperty())){
			String cnporperty=(String)BeanUtils.getDeclaredPropertyNoException(obj,wit.cnproperty());
			if(StringUtils.isNotEmpty(cnporperty))
				return com.witframework.util.Chinese2Spell.getChineseFirstChar(cnporperty);
			else
				return new TimestampBasedUIDGenerator().generate();
		}else if(obj instanceof com.witframework.core.BaseEntity){
			return ((com.witframework.core.BaseEntity)obj).getId();
		}else{
			return new TimestampBasedUIDGenerator().generate();
		}
	}

}
